import { useAppSelector } from '@/store';
import {
  addUserChannelAction,
  delUserChannelAction,
  getChannelAction,
  getUserChannelAction,
  handleKeyAction,
} from '@/store/action/channel';
import { ChannelListType } from '@/store/reducer/channel';
import { getLocalChannels, getToken, setLocalChannels } from '@/utils/storage';
import { Popup, Tabs, Toast } from 'antd-mobile';
import { differenceBy } from 'lodash';
import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { Icon } from '../Icon';
import styles from './index.module.scss';

export default function Channel() {
  const history = useHistory();
  //  声明editable状态，来做条件渲染
  const [editable, setEditable] = useState(false);
  // 弹出框的选择变量
  const [visible, setVisible] = useState(false);
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getChannelAction());
    dispatch(getUserChannelAction());
  }, [dispatch]);
  const { allChanList, currentId, userChanList } = useAppSelector((state) => state.channel);

  // 频道推荐 筛选除了用户选择剩下的 (计算属性)
  // const recomChanList = allChanList.filter(
  //   (item) => userChanList.findIndex((_item) => item.id === _item.id) === -1
  // );
  // 👍推荐使用lodash库 调用api计算  '_.differenceBy'代表全局调用 '_'代表引入的变量
  const recomChanList = differenceBy(allChanList, userChanList, 'id');

  // 删除用户频道
  const handleDelUserChannel = async (id: number) => {
    // 4. 不能删除推荐
    if (id === 0) {
      return Toast.show({ content: '不允许删除推荐频道' });
    }
    // 没有token情况的删除 删本地数据
    if (!getToken()) {
      // getLocalChannels() 本地获取的频道
      if (getLocalChannels().length === 5) {
        return Toast.show({ content: '至少保留5个' });
      }
      const localChannel = getLocalChannels().filter((item) => {
        return item.id !== id;
      });
      setLocalChannels(localChannel);
      dispatch({ type: 'channel/delUserChanList', payload: id });
      Toast.show({ content: '删除成功' });
      return;
    }

    // 5. 至少保留5个
    if (userChanList.length === 5) {
      return Toast.show({ content: '至少保留5个' });
    }
    await dispatch(delUserChannelAction(id));
    Toast.show({ content: '删除成功' });
  };
  // 编辑将弹出框关闭和编辑setEditable样式恢复
  const handleColse = () => {
    setVisible(false);
    setEditable(false);
  };

  // 添加推荐频道
  const handleAddChannel = (channels: ChannelListType) => {
    if (!getToken()) {
      setLocalChannels([...getLocalChannels(), ...channels]);
      dispatch({ type: 'channel/addUserChanList', payload: channels });
      return;
    }
    dispatch(addUserChannelAction(channels));
  };
  const handleChange = (key: string) => {
    dispatch(handleKeyAction(Number(key)));
  };
  return (
    <div className={styles.root}>
      {/* 这里onChange的key参数是antd库内定的 */}
      <Tabs activeKey={String(currentId)} className="tabs" onChange={(key) => handleChange(key)}>
        {userChanList.map((item) => (
          <Tabs.Tab title={item.name} key={item.id}></Tabs.Tab>
        ))}
      </Tabs>
      <div className="right">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon type="iconbtn_channel" onClick={() => setVisible(true)} />
      </div>
      <Popup visible={visible} position="left" bodyClassName={styles.channelPopup}>
        {/* 顶部栏：带关闭按钮 */}
        <div className="channel-header">
          <Icon type="iconbtn_channel_close" onClick={() => handleColse()} />
        </div>

        {/* 频道列表 */}
        <div className="channel-content">
          {/* 当前已选择的频道列表 */}
          <div className="channel-item edit">
            <div className="channel-item-header">
              <span className="channel-item-title">我的频道</span>
              <span className="channel-item-title-extra">点击删除频道</span>
              <span className="channel-item-edit" onClick={() => setEditable(!editable)}>
                {editable ? '完成' : '编辑'}
              </span>
            </div>

            <div className="channel-list">
              {userChanList.map((item) => (
                <span key={item.id} className="channel-list-item">
                  {item.name}
                  {editable && (
                    <Icon type="iconbtn_tag_close" onClick={() => handleDelUserChannel(item.id)} />
                  )}
                </span>
              ))}
            </div>
          </div>

          {/* 推荐的频道列表 */}
          <div className="channel-item">
            <div className="channel-item-header">
              <span className="channel-item-title">频道推荐</span>
              <span className="channel-item-title-extra">点击添加频道</span>
            </div>
            <div className="channel-list">
              {recomChanList.map((item) => (
                <span
                  key={item.id}
                  className="channel-list-item"
                  onClick={() => handleAddChannel([item])}
                >
                  + {item.name}
                </span>
              ))}
            </div>
          </div>
        </div>
      </Popup>
    </div>
  );
}
